﻿using System.Web.Security;
using ITTestingSystem.BusinessLogic.DataServices.Abstract;
using ITTestingSystem.BusinessLogic.Enums;

namespace ITTestingSystem.Extentions.Modules.AuthenticationProvider
{
    /// <summary>
    /// 
    /// </summary>
    /// 
    public class AuthenticationProvider : IAuthenticationProvider
    {
        /// <summary>
        /// 
        /// </summary>
        /// 
        private readonly IUserService _userService;

        /// <summary>
        /// 
        /// </summary>
        /// 
        /// <param name="userService">
        /// 
        /// </param>
        public AuthenticationProvider(IUserService userService)
        {
            _userService = userService;
        }

        /// <summary>
        /// 
        /// </summary>
        /// 
        /// <param name="login">
        /// 
        /// </param>
        /// 
        /// 
        /// <param name="password">
        /// 
        /// </param>
        /// <param name="isPersistent">
        /// 
        /// </param>
        /// 
        /// <returns>
        /// </returns>
        /// 
        AuthenticationResult IAuthenticationProvider.Authenticate(string login, string password, bool isPersistent)
        {
            var validateUserResult = ValidateUser(login, password);

            if (validateUserResult == AuthenticationResult.Authenticated)
            {
                FormsAuthentication.SetAuthCookie(login, isPersistent);
                return AuthenticationResult.Authenticated;
            }

            return validateUserResult;
        }

        void IAuthenticationProvider.SignOut()
        {
            FormsAuthentication.SignOut();
        }

        /// <summary>
        /// 
        /// </summary>
        /// 
        /// <param name="login">
        /// 
        /// </param>
        /// 
        /// <param name="password">
        /// 
        /// </param>
        /// 
        /// <returns>
        /// 
        /// </returns>
        /// 
        private AuthenticationResult ValidateUser(string login, string password)
        {
            var user = _userService.GetUserByLoginPassword(login, password);

            if (user == null)
            {
                return AuthenticationResult.NotAuthenticated;
            }

            if (user.AuthenticationsDetail.EmailConfirmed)
            {
                return AuthenticationResult.Authenticated;
            }

            return AuthenticationResult.EmailNotConfirmed;
        }
    }
}